<template>
  <div class="upload-item">
    <el-upload ref="uploadfiles"
               :accept="type"
               :class="{ borderNone: imageUrl }"
               class="avatar-uploader"
               action="/admin/common/upload"
               :show-file-list="false"
               :on-success="handleAvatarSuccess"
               :on-error="handleError"
               :before-upload="beforeAvatarUpload"
               :headers="headers">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <span v-if="imageUrl" class="el-upload-list__item-actions">
        <span class="el-upload-span" @click.stop="oploadImgDel">删除图片</span>
        <span class="el-upload-span">重新上传</span>
      </span>
    </el-upload>
    <p class="upload-tips">
      <slot></slot>
    </p>
  </div>
</template>

<script>



export default {
  name: 'UploadImage',
  props: {
    type: { type: String, default: '.jpg,.jpeg,.png' },
    size: { type: Number, default: 2 },
    propImageUrl: { type: String, default: '' },
  },
  mounted() {
    const user = localStorage.getItem("user");
    if (user){
      this.tokens=JSON.parse(user).data.token;//设置请求头
    }
    this.headers.token=this.tokens;
  },
  data() {
    return {
      headers: {token: ''},
      imageUrl: '',
      tokens:''
    };
  },
  watch: {
    propImageUrl(newVal) {
      this.imageUrl = newVal;
    },
  },
  methods: {
    handleError(err, file, fileList) {
      console.log(err, file, fileList, 'handleError');
      this.$message({
        message: '图片上传失败',
        type: 'error',
      });
    },
    handleAvatarSuccess(response, file, fileList) {
      console.log(response)
      this.imageUrl = response.data;
      this.$emit('imageChange', this.imageUrl);
    },
    oploadImgDel() {
      this.imageUrl = '';
      this.$emit('imageChange', this.imageUrl);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < this.size;
      if (!isLt2M) {
        this.$message({
          message: `上传文件大小不能超过${this.size}M!`,
          type: 'error',
        });
        return false;
      }
      return true;
    },
  },
};
</script>